package com.fajuary.xiyishop_big_android;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.esapos.androidpos.aidl.IPosAidlInterface;
import com.esapos.codepaypos.aidl.ICodePayPos;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * @author 黄辉
 * @time 2016/12/22 10:58
 * <p>
 * pos机收款
 */
public class ReceiptActivity extends Activity {
    private static final int DISMISS_DIALOG = 0;
    private static final int SHOW_DIALOG = 1;
    private static final int INIT_SUCC = 2;
    private static final int INIT_FAIL = 3;

    public static final String RET_SUCCESS = "00";
    private LinearLayout activity_receipt;
    private LinearLayout iv_back;
    private TextView tv_weikuan_bufen;
    private CheckBox cb_section_one;
    private TextView tv_weikuan_quanbu;
    private CheckBox cb_section_two;
    private TextView tv_queding;
    private String shopName;
    private String orderSpareId;
    private String token;
    private String money;
    private String title = null;
    private double i;
    private double b;
    private int c;

    private ICodePayPos iCodePayPos;

    private ProgressDialog loadingDlg;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_DIALOG:
                    showDlg();
                    break;
                case DISMISS_DIALOG:
                    dismissDlg();
                    break;
                case INIT_SUCC:
                    dismissDlg();
                    showMsg("初始化成功");
                    // 可以在这里做初始化后直接进入交易流程
//                    dealSale();
                    break;
                case INIT_FAIL:
                    dismissDlg();
                    showMsg("初始化失败，请重试...");
                    break;
            }
        }
    };
    private MyBroadCastReceiver myBroadCastReceiver;   //广播
    private String result;
    private String outTradeNo;
    private int totalFee;
    private String time;
    private String voucherNo;
    private String ordercode;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    //  "1 "   代表银联支付
    private void dealSale() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject paramJson = new JSONObject();
                    try {
                        paramJson.put("amount", money);

                        final String result = posAidl.payCash(paramJson
                                .toString());

//                        JSONObject json =  new JSONObject(result);
//                        String retCode = json.optString("retCode");
                        PosYLBean posYLBean = JSON.parseObject(result, PosYLBean.class);
                        String retCode = posYLBean.getRetCode();
                        Log.e("TAG", "shuju" + result);
                        if (RET_SUCCESS.equalsIgnoreCase(retCode)) {
                            // 消费成功，处理交易结果，可以保存、打印凭条等
                            voucherNo = posYLBean.getBody().getVoucherNo();
                            Log.e("TAG", "shuju==============================" + voucherNo);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    XY_DApi.posbigpay(token, ordercode, voucherNo, "1", new AsyncHttpResponseHandler() {
                                        @Override
                                        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                                            if (null != responseBody && responseBody.length > 0) {
                                                Log.e("TAG", new String(responseBody) + "返回的数据" + "============================");
                                                //解析json
                                                explainJson(new String(responseBody));
                                            }
                                        }

                                        @Override
                                        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                                            Log.e("TAG", "w尾款返回的数据:::" + statusCode + error.toString());
                                        }
                                    });
                                }
                            });

                        } else {
                            // 消费失败

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 解析  银联
     *
     * @param Json
     */
    private void explainJson(String Json) {
        PosZhiFuBean posZhiFuBean = JSON.parseObject(Json, PosZhiFuBean.class);
        String code = posZhiFuBean.getCode();
        if (code.equals("1")) {
            finish();
        }
    }

    private void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private void setDialog(String msg) {
        loadingDlg = new ProgressDialog(this);
        loadingDlg.setMessage(msg);
        loadingDlg.setCancelable(false);
        loadingDlg.show();
    }

    private void showDlg() {
        if (null != loadingDlg) {
            loadingDlg.show();
        }
    }

    private void dismissDlg() {
        if (null != loadingDlg) {
            loadingDlg.cancel();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receipt);
        // 绑定到服务
        bindService(new Intent("com.esapos.codepaypos.aidl.CodePayPosService"),
                this.serviceConnection, BIND_AUTO_CREATE);
        // 建立服务连接
        bindService();

//        initView();
        bindViews();

        myBroadCastReceiver = new MyBroadCastReceiver();
        IntentFilter intentFilter = new IntentFilter(
                "com.esapos.codepaypos.result");
        registerReceiver(myBroadCastReceiver, intentFilter);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 解除服务
        unbindService(serviceConnection);
        //接触广播
        unregisterReceiver(myBroadCastReceiver);
    }

    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    public Action getIndexApiAction() {
        Thing object = new Thing.Builder()
                .setName("Receipt Page") // TODO: Define a title for the content shown.
                // TODO: Make sure this auto-generated URL is correct.
                .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
                .build();
        return new Action.Builder(Action.TYPE_VIEW)
                .setObject(object)
                .setActionStatus(Action.STATUS_TYPE_COMPLETED)
                .build();
    }



    //使用广播返回交易信息
    public class MyBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            result = intent.getStringExtra("result");
            outTradeNo = intent.getStringExtra("outTradeNo");
            totalFee = intent.getIntExtra("totalFee", 0);
            time = intent.getStringExtra("time");
            if (outTradeNo != null) {
                XY_DApi.posbigpay(token, orderSpareId, outTradeNo, "2", new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                        if (null != responseBody && responseBody.length > 0) {
                            Log.e("TAG", new String(responseBody) + "返回的数据" + "============================");
                            //解析json
                            explainJson(new String(responseBody));
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                        Log.e("TAG", "w尾款返回的数据:::" + statusCode + error.toString());
                    }
                });
            }
        }
    }

    private void initView() {
        bindService();

        setDialog("交易初始化...");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    mHandler.sendEmptyMessage(SHOW_DIALOG);

                    String result = posAidl.signIn("");
                    try {
                        JSONObject json = new JSONObject(result);
                        String retCode = json.optString("retCode");
                        Log.e("初始化交易", retCode);
                        if (RET_SUCCESS.equalsIgnoreCase(retCode)) {
                            // 签到成功，请在这里添加后续处理流程
                            mHandler.sendEmptyMessage(INIT_SUCC);
                        } else {
                            // 签到失败  INIT_SUCC
                            mHandler.sendEmptyMessage(INIT_FAIL);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        mHandler.sendEmptyMessage(INIT_FAIL);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    mHandler.sendEmptyMessage(INIT_FAIL);
                }
            }
        }).start();

    }

    private void bindService() {
        // 绑定到服务
        bindService(new Intent("com.esapos.codepaypos.aidl.CodePayPosService"),
                this.serviceConnection, BIND_AUTO_CREATE);
        if (null == posAidl) {
            final Intent intent = new Intent("com.esapos.intent.posService");
            bindService(intent, connection, BIND_AUTO_CREATE);
        }

    }

    private void bindViews() {
        ordercode = getIntent().getStringExtra("ordercode");
        token = CacheUtils.getstr(this, "id");
        money = getIntent().getStringExtra("money");
        i = Double.parseDouble(money);
        b = i * 100;
        c = (int) b;
        activity_receipt = (LinearLayout) findViewById(R.id.activity_receipt);
        iv_back = (LinearLayout) findViewById(R.id.iv_back);
        tv_weikuan_bufen = (TextView) findViewById(R.id.tv_weikuan_bufen);
        cb_section_one = (CheckBox) findViewById(R.id.cb_section_one);
        tv_weikuan_quanbu = (TextView) findViewById(R.id.tv_weikuan_quanbu);
        cb_section_two = (CheckBox) findViewById(R.id.cb_section_two);
        tv_queding = (TextView) findViewById(R.id.tv_queding);

        cb_section_one.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (cb_section_one.isChecked()) {
                    cb_section_two.setChecked(false);
                    title = "1";
                }
                initView();
            }
        });
        cb_section_two.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (cb_section_two.isChecked()) {
                    cb_section_two.setChecked(true);
                    cb_section_one.setChecked(false);
                }
                title = "2";
//                initView();
            }
        });
        /**
         * 确定
         */
        tv_queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(title)) {
                    if (title.equals("1")) {
                        dealSale();
                    } else if (title.equals("2")) {
                        try {
                            iCodePayPos.qrPayPos(c, "商家收款1", shopName, "门店1");
                        } catch (RemoteException e) {
                            Log.e("MainActivity", e.toString());
                        }
                    }
                } else {
                    Toast.makeText(ReceiptActivity.this, "请选择收款方式", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iCodePayPos = ICodePayPos.Stub.asInterface(service);

        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {

        }
    };

    private IPosAidlInterface posAidl;
    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            posAidl = IPosAidlInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };


}
